package com.alibaba.druid.sql.dialect.kingbasesql.methodinvoke.imp;

import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.dialect.kingbasesql.methodinvoke.IMethodInvoke;
import com.alibaba.druid.sql.dialect.kingbasesql.visitor.KingbaseOutputVisitor;

/**
 * kingbase 不支持 find_in_set()，需要自定义函数
 *
 * <code>
 *      CREATE OR REPLACE FUNCTION find_in_set(str text, strlist text) RETURNS BOOLEAN LANGUAGE plpgsql AS
 *      $func$
 *      BEGIN
 *          return array_position(string_to_array($2, ','), $1) > 0;
 *      END;
 *      $func$
 * </code>
 * @author jiangtao
 */
public class FindInSetMethodInvoke implements IMethodInvoke {

    @Override
    public boolean invoke(SQLMethodInvokeExpr x, KingbaseOutputVisitor visitor) {
        boolean ucase = visitor.isUppCase();

        visitor.print(ucase ? " FIND_IN_SET (" : " find_in_set (");

        // 拼接参数
        for (int i = 0; i < x.getArguments().size(); i++) {
            visitor.toPrintExpr(x.getArguments().get(i));

            if(i != x.getArguments().size() -1) {
                visitor.print(" || '', ");
            } else {
                visitor.print(" || ''");
            }
        }

        visitor.print(")");
        return true;
    }
}
